<?php

require_once "broker.class.php";
require_once "exception.class.php";
require_once "router.class.php";
require_once "response.class.php";
require_once "request.class.php";
require_once "dispatcher.class.php";
require_once "config.class.php";

class FrontController
{
    
    private static $_instance = null;
    private $_router;
    private $_broker;
    private $_response;
    private $_request;
    
    private function FrontController () {
        $cfg = Config::getInstance();
        $url_files = $cfg->urlfiles;

        $this->_broker = new Broker();
        $this->_router = new Router();
        foreach ($url_files as $file) {
            $this->_router->appendFile($file);
        }
        $this->_response = new Response();
        $this->_request = new Request();
        $this->broker()->setResponse($this->response());
        $this->broker()->setRequest($this->request());

    }
    public function request () {
        return $this->_request;
    }
    public function response () {
        return $this->_response;
    }
    public function router () {
        return $this->_router;
    }
    public function broker () {
        return $this->_broker;
    }
    
    static public function getInstance () {
        if (FrontController::$_instance == null) {
            FrontController::$_instance = new FrontController();
        }
        return FrontController::$_instance;
    }
    
    
    public function mvcRun () {
        $dispatcher = new Dispatcher();
        $broker = $this->broker();
        try {
            $broker->routeStartup();
            $this->router()->route($this->request(), $this->response());
            $broker->routeShutdown();
            $broker->dispatchLoopStartup();
    
            do {
                $this->request()->setDispached(true);
                $broker->preDispatch();
                if (!$this->request()->isDispached()) {
                    continue;
                }
                try {
                    $dispatcher->dispatch($this->request(), $this->response());
                } catch (Exception $e) {
                    $this->response()->appendException($e);
                }
                $broker->postDispatch();
                
            } while (!$this->request()->isDispached());
            
        } catch (Exception $e) {
            $this->response()->appendException($e);
        }

        try {
            $broker->dispatchLoopShutdown();
        } catch (Exception $e) {
            $this->response()->appendException($e);
        }
        

    }
    
}
